package com.markyao.controller.recos.raft;

import com.markyao.recos.raft.raftRole.AbstractRaftRole;
import com.markyao.service.AuthService;
import com.markyao.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j(topic = "m.RaftController")
@RestController
@RequestMapping("/recos/raft")
public class RaftController {
    @Autowired
    AbstractRaftRole raftRole;

    @Autowired
    AuthService authService;

    @Autowired
    @Qualifier("raftHearBeat")
    AtomicInteger raftHearBeat;

    @Autowired
    @Qualifier("leaderMetadata")
    ConcurrentHashMap<String,Object> leaderMap;


    @PostMapping("recvHeartBeat")
    public Result recvHeartBeat(HttpServletRequest request){
        raftHearBeat.set(1);
        return Result.success(null);
    }
    @PostMapping("recvHeartBeat0")
    public Result recvHeartBeat0(@RequestBody Map<String,Object>body, HttpServletRequest request){
        raftHearBeat.set(1);
        raftRole.setVote(true);
        String host = body.get("host").toString();
        int port = (int) body.get("port");
        leaderMap.put("host",host);
        leaderMap.put("port",port);
        leaderMap.put("alive",true);
        return Result.success(null);
    }

    @GetMapping("vote")
    public Result vote(@RequestParam("startTime")Long startTime,HttpServletRequest request,
                       @RequestParam("targetAddress")String targetAddress){
        Result result = raftRole.vote(startTime,targetAddress);
        return result;
    }

    @GetMapping("askLeader")
    public Result askLeader(){
        log.info("收到询问,马上发送心跳.");
        raftRole.sendHeartBeat(0);
        return Result.success(null);
    }


}
